/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VendasCadastra.java
 *
 * Created on 15/06/2011, 16:44:35
 */

package pacote;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pardall
 */
public class VendasCadastra extends javax.swing.JFrame {

    private EntityManagerFactory emf;
    private EntityManager em;
    private List<Produtos> produtos;
    private List<Clientes> clientes;
    private float total;

    /** Creates new form VendasCadastra */
    public VendasCadastra(EntityManager exm) {
        initComponents();        
        em = exm;
        produtos = getProd();
        clientes = getClientes();
        updateSel();
        total = 0;
    }

    private List<Produtos> getProd(){
        TypedQuery<Produtos> query = em.createNamedQuery("Produtos.findAll", Produtos.class);
        return query.getResultList();
    }

    private List<Clientes> getClientes(){
        TypedQuery<Clientes> query = em.createNamedQuery("Clientes.findAll", Clientes.class);
        return query.getResultList();
    }

    private void updateSel(){
        for (Produtos p : produtos){
            prodSel.addItem(p.getNome());
        }
        StringBuilder nomeCli = new StringBuilder();
        for (Clientes c : clientes){
            nomeCli.append(c.getNome());
            nomeCli.append(c.getSnome());
            cliSel.addItem(nomeCli.toString());
            nomeCli.setLength(0);
        }
    }


    private void updateProd (){
        Produtos temp = new Produtos();
        em.getTransaction().begin();
        for (Produtos p : produtos){
            temp = em.find(Produtos.class, p.getId());
            temp = p;
            em.persist(temp);
        }
        em.getTransaction().commit();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        prodSel = new javax.swing.JComboBox();
        cliSel = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        qtde = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        addItem = new javax.swing.JButton();
        createVenda = new javax.swing.JButton();
        ValTotal = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        prodSel.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                prodSelItemStateChanged(evt);
            }
        });

        jLabel1.setText("Cliente:");

        jLabel2.setText("Produto:");

        jLabel3.setText("Qtde.");

        qtde.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                qtdeActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod.", "Produto", "Quantidade", "Valor Unid.l", "Total Parcial"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(10);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(20);

        addItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/add.png"))); // NOI18N
        addItem.setText("Adicionar");
        addItem.setEnabled(false);
        addItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addItemActionPerformed(evt);
            }
        });

        createVenda.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/check.png"))); // NOI18N
        createVenda.setText("Registrar Venda");
        createVenda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createVendaActionPerformed(evt);
            }
        });

        ValTotal.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        ValTotal.setText("Total:");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imgs/cadastrar.png"))); // NOI18N
        jLabel4.setText("Cadastro de Vendas");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addContainerGap(249, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(5, 5, 5)
                                        .addComponent(jLabel1))
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(prodSel, 0, 289, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(qtde, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(cliSel, 0, 386, Short.MAX_VALUE)
                                    .addComponent(addItem, javax.swing.GroupLayout.Alignment.TRAILING)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ValTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                                .addGap(167, 167, 167)
                                .addComponent(createVenda))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cliSel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(prodSel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(qtde, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addItem)
                .addGap(42, 42, 42)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(createVenda)
                    .addComponent(ValTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addItemActionPerformed
        if (evt.getSource() == this.addItem){
            float subtotal = 0;
            Produtos p = produtos.get(prodSel.getSelectedIndex());
            Object[] row = new Object[5];
            DefaultTableModel venda = (DefaultTableModel)jTable1.getModel();
            subtotal = Integer.parseInt(qtde.getText())*p.getPreco();
            row[0] = p.getId();
            row[1] = p.getNome();
            row[2] = qtde.getText();
            row[3] = ""+p.getPreco();
            row[4] = ""+subtotal;
            venda.addRow(row);
            total = total + subtotal;
            ValTotal.setText("TOTAL: R$"+total);
            p.setQtdEstoque((short) (p.getQtdEstoque() - Integer.parseInt(qtde.getText())));
        }
    }//GEN-LAST:event_addItemActionPerformed

    private void qtdeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_qtdeActionPerformed
        if (evt.getSource() == this.qtde) {
            try {
                if (Integer.parseInt(qtde.getText()) > produtos.get(prodSel.getSelectedIndex()).getQtdEstoque()) {
                    JOptionPane.showMessageDialog(null,
                            "Quantidade no estoque: " + produtos.get(prodSel.getSelectedIndex()).getQtdEstoque(),
                            "Estoque insuficiente!",
                            JOptionPane.PLAIN_MESSAGE);
                    addItem.setEnabled(false);
                } else {
                    addItem.setEnabled(true);
                }

            } catch (Exception ex) {
                //JOptionPane.showMessageDialog(null, "Somente números!");
            }
        }
    }//GEN-LAST:event_qtdeActionPerformed

    private void updateItems(short idVenda){
        DefaultTableModel venda = (DefaultTableModel)jTable1.getModel();                
        em.getTransaction().begin();
        for (int i = 0; i < venda.getRowCount(); i++){
            Itemsvendas item = new Itemsvendas();
            //item.setId(null);
            item.setQtdeProduto(Short.parseShort((String)venda.getValueAt(i,2)));
            item.setIdProduto((Short)venda.getValueAt(i,0));
            item.setIdVenda(idVenda);            
            em.persist(item);            
        }
        em.getTransaction().commit();
    }

    private void createVendaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createVendaActionPerformed
        if (evt.getSource() == this.createVenda) {
            Vendas v = new Vendas();
            v.setSituacao(false);
            v.setIdUser(clientes.get(cliSel.getSelectedIndex()).getId());
            v.setDatap(new Date());
            em.getTransaction().begin();
            em.persist(v);            
            em.getTransaction().commit();
            updateItems(v.getId());
            updateProd();

            JOptionPane.showMessageDialog(null, "Venda registrada.");
            this.dispose();
        }
    }//GEN-LAST:event_createVendaActionPerformed

    private void prodSelItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_prodSelItemStateChanged
        try {
                if (Integer.parseInt(qtde.getText()) > produtos.get(prodSel.getSelectedIndex()).getQtdEstoque()) {
                    addItem.setEnabled(false);
                } else {
                    addItem.setEnabled(true);
                }

            } catch (Exception ex) {

            }
    }//GEN-LAST:event_prodSelItemStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ValTotal;
    private javax.swing.JButton addItem;
    private javax.swing.JComboBox cliSel;
    private javax.swing.JButton createVenda;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JComboBox prodSel;
    private javax.swing.JTextField qtde;
    // End of variables declaration//GEN-END:variables

}
